<template>
    <div class="planList-index yuan-container">
        <div class="filter-panel">
            <span class="planList-title">
                {{planSimulation.planName}}
            </span>
            <div class="filter-list">
                <span class="filter-tips ">需求量：
                    <span class="font-bignum c-primary">{{planSimulation.xuqiu | toDecimalNoZero}}</span>
                    <span>kg</span>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips ">投料量：
                    <span class="font-bignum c-primary">{{(pageData.touliao  )|| '--' }}</span>
                    <span>kg</span>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">剩余需求量:
                    <span class="font-bignum c-warning">{{(pageData.shenchan  )|| '--'}}</span>
                    <span>kg</span>
                </span>
            </div>
        </div>

        <div class="planList-top filter-panel" v-for="item in alarmDataCopy">
            <span class="planList-title">
                {{item.inventoryType}}({{planSimulation.planSerial+item.inventoryType}})
            </span>
            <div class="filter-list">
                <span class="filter-tips">预计完成时间：
                    <span class="mast-ico"></span>
                    <a-date-picker class="yuan-form-input" placeholder="预计完成时间" v-model="item.finishTime"
                        valueFormat="YYYY-MM-DD" />
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">预计包装后成品可销售天数：{{item.sellDay}}天</span>
            </div>
        </div>

        <div style="border-bottom:solid 1px #999;margin-bottom:20px"></div>
        <div style="font-size:16px;font-weight:bold;margin-bottom:20px">
            <span>
                {{planSimulation.materialName}} 库存现状
            </span>
        </div>
        <div style="margin-bottom:20px">
            <span>是否使用现有库存批次：</span>
            <a-radio-group v-model="pageData.useStore" @change="useStoreChange">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
            </a-radio-group>
        </div>
        <template v-if="pageData.useStore===true">

            <div class="filter-panel">
                <div class="filter-list">
                    <span>颗粒批号：</span>
                    <a-input-search allowClear v-model="pageParams.batch" placeholder="请输入关键字" @search="resetList" />
                </div>
                <div class="filter-list">
                    <span>可供销售天数：</span>
                    <span class="filter-range">
                        <a-input v-model="pageParams.sellDayStart"></a-input>
                        <span class="filter-tips">~</span>
                        <a-input v-model="pageParams.sellDayEnd"></a-input>
                        <span class="filter-tips">天</span>
                    </span>
                </div>
                <div class="filter-list">
                    <span>质量状态：</span>
                    <a-select v-model="pageParams.qualityState" @change="resetList" allowClear placeholder="请选择质量状态">
                        <a-select-option value="1">合格</a-select-option>
                        <a-select-option value="2">不合格</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span>有效期：</span>
                    <a-range-picker :mode="['month','month']" :open="monthPickShow" @panelChange="handlePanelChange"
                        v-model="billMonth" @openChange="handleOpenChange" :placeholder="['开始日期','结束日期']"
                        :format="['YYYY-MM','YYYY-MM']" />
                </div>
                <div class="filter-list">
                    <a-button type="primary" @click="getList" class="filter-list">搜索</a-button>
                </div>
            </div>

            <div class="table">
                <a-radio-group v-model="tableSelect" @change="pageListSelectChange" style="width:100%">
                    <a-table bordered :rowKey="(row)=>row.id" :data-source="pageList" :columns="packageColumns"
                        :pagination="false" :loading="loading">
                        <template slot="select" slot-scope="text, record, index">
                            <a-radio :value="index"></a-radio>
                        </template>
                        <template :slot="'number'+item.inventoryType" slot-scope="text, record, index"
                            v-for="item in alarmDataCopy">
                            <span v-if="!pageList[index].isSelect || item.formDifferenceNum<=0">--</span>
                            <a-input type="number" style="width:100px" placeholder="请输入数量"
                                v-model="pageList[index][item.inventoryType+'_num']" @input="inputNumChange" v-else />

                        </template>
                        <template slot="qualityState" slot-scope="text, record, index">
                            <span>{{record.qualityState === "1" ? "合格" : "待检"}}</span>
                        </template>
                    </a-table>
                </a-radio-group>
            </div>
        </template>

    </div>
</template>
<script lang="ts">
import warningApi from "@/api/warningApi";
import { toDecimalNoZero } from "@/utils";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";

@Component({
    name: "dom",
    components: {},
})
export default class index extends Vue {
    @Prop({ default: "" }) planSimulation!: any;
    @Prop({ default: "" }) alarmData!: any;
    @Watch("planSimulation")
    visibleChange() {
        if (this.planSimulation) {
            const newArr = JSON.parse(JSON.stringify(this.packageColumnsDef));
            this.alarmDataCopy = JSON.parse(JSON.stringify(this.alarmData));
            this.alarmData.forEach((item) => {
                newArr.push({
                    align: "center",
                    dataIndex: "inventoryType" + item.inventoryType,
                    key: "inventoryType" + item.inventoryType,
                    title: item.inventoryType + "投料量（kg）",
                    scopedSlots: { customRender: "number" + item.inventoryType },
                });
            });
            this.packageColumns = newArr;
            this.getList();
        }
    }
    alarmDataCopy: any[] = [];
    packageColumns = [];
    // 包装计划表格
    packageColumnsDef = [
        {
            align: "center",
            dataIndex: "select",
            key: "select",
            title: "",
            scopedSlots: { customRender: "select" },
        },
        {
            align: "center",
            dataIndex: "batch",
            key: "batch",
            title: "颗粒批号",
        },
        {
            align: "center",
            dataIndex: "scTime",
            key: "scTime",
            title: "生产日期",
        },
        {
            align: "center",
            dataIndex: "validTime",
            key: "validTime",
            title: "有效期至",
        },
        {
            align: "center",
            dataIndex: "qualityState1",
            key: "qualityState1",
            title: "复验期",
        },
        {
            align: "center",
            dataIndex: "surplus",
            key: "surplus",
            title: "库存数量",
            customRender: (text: string, record: any, index: number) => toDecimalNoZero(record.surplus, 2),
        },
        {
            align: "center",
            dataIndex: "qualityState3",
            key: "qualityState3",
            title: "可销售天数",
        },
        {
            align: "center",
            dataIndex: "qualityState",
            key: "qualityState",
            title: "质量状态",
            scopedSlots: { customRender: "qualityState" },
        },
    ];
    loading = false;
    pageParams: any = {
        batch: "",
        qualityState: undefined,
        sellDayStart: "",
        sellDayEnd: "",
        startTime: "",
        endTime: "",
    };
    pagination = {
        pageSize: 999,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    pageList: any[] = [];
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    async getList() {
        this.tableSelect = "";
        this.pageList = [];
        try {
            this.loading = true;
            const res = await warningApi.materialStockList({
                ...this.pageParams,
                pageSize: this.pagination.pageSize,
                page: this.pagination.current,
                materialName: this.planSimulation.materialName,
                materialType: this.planSimulation.materialType,
            });
            // 如果没有库存 直接下一步
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.records || [];
            if (this.pageList.length === 0) {
                this.pageData.touliao = "0";
                this.pageData.shenchan = toDecimalNoZero(this.planSimulation.xuqiu);
                this.$emit("inputNumChange", {
                    id: this.planSimulation.materialId,
                    need: this.planSimulation.xuqiu,
                    nextPlan: ["制剂计划", "提取计划", "饮片计划"],
                });
            }
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    useStoreChange() {
        if (this.pageData.useStore) {
            this.pageListSelectChange();
        } else {
            this.pageData.touliao = "0";
            this.pageData.shenchan = toDecimalNoZero(this.planSimulation.xuqiu);
            this.$emit("inputNumChange", {
                id: this.planSimulation.materialId,
                need: this.planSimulation.xuqiu,
                nextPlan: ["制剂计划", "提取计划", "饮片计划"],
            });
        }
    }

    billMonth = [];
    monthPickShow = false;
    handlePanelChange(value, mode) {
        if (mode[1] === "date") {
            const arr = value.map((item) => item.format("YYYY-MM"));
            this.billMonth = arr;
            this.pageParams.startTime = arr[0];
            this.pageParams.endTime = arr[1];
            this.resetList();
            this.monthPickShow = false;
        }
    }
    handleOpenChange(status) {
        if (status) {
            this.monthPickShow = true;
        } else {
            this.monthPickShow = false;
        }
    }

    tableSelect = "";
    pageListSelectChange() {
        if (this.tableSelect === "") return;

        const pageList = [...this.pageList];
        const type = pageList[this.tableSelect].isSelect;
        pageList.map((item) => {
            item.isSelect = false;
        });
        if (!type) {
            let store = pageList[this.tableSelect].surplus;
            //如果选择的库存小于需求量 提示
            if (store < this.planSimulation.xuqiu) {
                this.$message.error("该批次库存量无法满足投料需求量，请选择库存量充足批次或重新生产");
                this.tableSelect = "";
                return;
            }
            pageList[this.tableSelect].isSelect = true;

            //优先投大袋
            const arr = ["C70", "C90", "C91", "C92"];
            const bigOne = this.alarmData.find((item) => {
                return arr.indexOf(item.inventoryType) >= 0;
            });
            let inNum = 0;
            if (bigOne) {
                if (store > bigOne.formInputNum) {
                    inNum = bigOne.formInputNum;
                } else {
                    inNum = store;
                }
                pageList[this.tableSelect][bigOne.inventoryType + "_num"] = inNum;
                store -= inNum;
            }

            //投完大袋再投小袋
            this.alarmData.forEach((item) => {
                if (item.inventoryType === bigOne.inventoryType) return;
                if (store > item.formInputNum) {
                    inNum = item.formInputNum;
                } else {
                    inNum = store;
                }
                pageList[this.tableSelect][item.inventoryType + "_num"] = inNum;
                store -= inNum;
            });
        }
        this.pageList = pageList;
        this.inputNumChange();
    }

    pageData: any = {
        useStore: true,
        touliao: "",
        shenchan: "",
    };
    mounted() {
        const newArr = JSON.parse(JSON.stringify(this.packageColumnsDef));
        this.alarmDataCopy = JSON.parse(JSON.stringify(this.alarmData));
        this.alarmData.forEach((item) => {
            newArr.push({
                align: "center",
                dataIndex: "inventoryType" + item.inventoryType,
                key: "inventoryType" + item.inventoryType,
                title: item.inventoryType + "投料量（kg）",
                scopedSlots: { customRender: "number" + item.inventoryType },
            });
        });
        this.packageColumns = newArr;
        this.getList();
    }
    simulationTimer: number | null = null;
    inputNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            let total = 0;
            this.alarmData.forEach((item) => {
                total += Number(this.pageList[this.tableSelect][item.inventoryType + "_num"]) || 0;
            });
            if (total > this.planSimulation.xuqiu) {
                this.$message.error("投料数量不能大于需求量");
                return;
            }
            if (total > this.pageList[this.tableSelect].surplus) {
                this.$message.error("投料数量不能大于库存量");
                return;
            }

            this.pageData.touliao = toDecimalNoZero(total);
            this.pageData.shenchan = toDecimalNoZero(this.planSimulation.xuqiu - total);
            this.$emit("inputNumChange", {
                id: this.planSimulation.materialId,
                need: this.planSimulation.xuqiu - total,
                nextPlan: ["制剂计划", "提取计划", "饮片计划"],
            });
        }, 500);
    }
    getPageInfo() {
        let verfyType = true;
        let verfyWords = "";
        let processPlanDetailList: any[] = [];
        // 没有库存的情况暂不考虑
        // 如果不使用现有库存 不进行判断
        if (this.pageData.useStore === false) {
            const item = this.pageList[0];
            this.alarmDataCopy.forEach((alarmDataItem) => {
                if (!alarmDataItem.finishTime) {
                    verfyType = false;
                    verfyWords = "请选择包装计划预计完成时间";
                    return false;
                }

                let processPlanInputList = [
                    {
                        stockId: "",
                        batch: "",
                        inputNum: 0,
                        isPro: false,
                        materialName: item.materialName,
                        materialType: item.materialType,
                        materialId: item.materialId,
                    },
                ];
                const plan = this.planSimulation;

                processPlanDetailList.push({
                    isPro: false,
                    finishTime: alarmDataItem.finishTime,
                    planName: plan.planName,
                    name: plan.planName,
                    inputNum: alarmDataItem.formInputNum,
                    needNum: alarmDataItem.formInputNum,
                    planSerial: plan.planSerial + alarmDataItem.inventoryType,
                    prodNum: alarmDataItem.formDifferenceNum,
                    processPlanInputList,
                    inventoryType: alarmDataItem.inventoryType,
                });
            });
            if (!verfyType) {
                this.$message.error(verfyWords);
                return false;
            }
            return processPlanDetailList;
        }

        // 如果使用当前库存

        const item = this.pageList[this.tableSelect];
        if (!item) {
            this.$message.error("包装计划还没有选择投料");
            return false;
        }

        let total = 0;

        this.alarmDataCopy.forEach((alarmDataItem) => {
            if (!alarmDataItem.finishTime) {
                verfyType = false;
                verfyWords = "请选择包装计划预计完成时间";
            }
            const num = item[alarmDataItem.inventoryType + "_num"];
            total += Number(num) || 0;
            let processPlanInputList = [
                {
                    stockId: item.id,
                    isPro: true,
                    batch: item.batch,
                    inputNum: num,
                    materialName: item.materialName,
                    materialType: item.materialType,
                    materialId: item.materialId,
                },
            ];

            const plan = this.planSimulation;
            processPlanDetailList.push({
                isPro: true,
                finishTime: alarmDataItem.finishTime,
                planName: plan.planName,
                name: plan.planName,
                inputNum: alarmDataItem.formInputNum,
                needNum: alarmDataItem.formInputNum - num,
                planSerial: plan.planSerial + alarmDataItem.inventoryType,
                prodNum: alarmDataItem.formDifferenceNum,
                processPlanInputList,
                inventoryType: alarmDataItem.inventoryType,
                prodId: plan.prodId,
                prodName: plan.prodName,
            });
        });
        if (!verfyType) {
            this.$message.error(verfyWords);
            return false;
        }
        if (total > this.planSimulation.xuqiu) {
            this.$message.error("包装计划投料数量不能大于需求量");
            return false;
        }
        if (total > item.surplus) {
            this.$message.error("包装计划投料数量不能大于库存量");
            return false;
        }

        return processPlanDetailList;
    }
}
</script>
<style lang="scss">
.planList-index {
    .planList-top {
        font-size: 16px;
        padding-bottom: 10px;
    }
    .planList-title {
        font-weight: bold;
        font-size: 20px;
    }

    .overview-panel {
        background-color: #fff;
        padding: 10px 10px;
    }
    .overview-title {
        margin-right: 30px;
    }
    .overview-titlebox {
        padding: 10px 0;
    }
}
</style>
